package com.SFA.Message;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import com.umeng.analytics.MobclickAgent;

import android.content.Context;

import com.FrameWork.Common.IAppImpl;
import com.FrameWork.Common.MyApplication;
import com.FrameWork.Entity.GlobalInfo;
import com.FrameWork.Entity.MessageEntity;

public class MessageLogicManager {

	private String CacheFileName = "/message";
	
	//是否更新成功
	public boolean Successful = false;
	
	
	public boolean Write2Cache(Context context, String content)
	{
		String Path = context.getCacheDir().toString();
		Path = Path + CacheFileName + GlobalInfo.GetInstance(context).getUserID();
		File file = new File(Path);
		OutputStreamWriter outputStreamWriter = null;

		if (file.exists())
		{
			file.delete();
		}
		else
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}

		try
		{
			outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
			outputStreamWriter.write(content, 0, content.length());
			outputStreamWriter.flush();
			return true;
		}
		catch (IOException e)
		{
			MobclickAgent.reportError(context, e.getMessage());
			return false;
		}
		finally
		{
			try {
				outputStreamWriter.close();
				outputStreamWriter = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				MobclickAgent.reportError(context, e.getMessage());
			}
		}
	}

	public List<MessageEntity> ReadFormCache(Context context)
	{
		List<MessageEntity> list = new ArrayList<MessageEntity>();
		// 不存在
		String Path = context.getCacheDir().toString();
		Path = Path + CacheFileName +  GlobalInfo.GetInstance(context).getUserID();
		File file = new File(Path);
		if (!file.exists())
			return list;

		BufferedReader bufferedReader = null;
		try
		{
			bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String reslut = null;
			StringBuffer stringBuffer = new StringBuffer();
			while ((reslut = bufferedReader.readLine()) != null)
			{
				stringBuffer.append(reslut);
			}
			JSONArray array = new JSONArray(stringBuffer.toString());
			for(int i=0;i<array.length();i++)
			{
				JSONObject object = array.getJSONObject(i);
				MessageEntity entity = new MessageEntity();
				if(!object.isNull("ImageURL"))
					entity.ImageURL = object.getString("ImageURL");
				entity.Title = object.getString("Title");
				entity.URL = object.getString("URL");
				if(object.has("Time"))
					entity.Time = object.getString("Time");
				entity.ReadFlag = object.getBoolean("ReadFlag");
				list.add(entity);
			}
			return list;
		}
		catch (Exception e)
		{
			MobclickAgent.reportError(context, e.getMessage());
			return null;
		}
		finally
		{
			try
			{
				bufferedReader.close();
				bufferedReader = null;
			}
			catch (Exception e)
			{
				MobclickAgent.reportError(context, e.getMessage());
				
			}
		}
	}

	/***
	 * 
	 * @param URL
	 *            解析地址
	 * @param pageIndex
	 *            页码
	 * @return RSSFeed 对象
	 * 
	 *         b 为true 是解析缓存
	 */
	public List<MessageEntity> getMessageByString(String URL,Context context)
	{
		Successful = false;
		List<MessageEntity> list = new ArrayList<MessageEntity>();
		IAppImpl app = new IAppImpl();
		try
		{
			String content = app.GetResouceByURL(URL, context, "GetMessageList", new Object[]{"UserID"}, new Object[]{ GlobalInfo.GetInstance(context).getUserID()});
			// 解析成功 ，处理缓存
			if(content == null)
			{
				list = ReadFormCache(context);
				return list;
			}
			JSONObject json = new  JSONObject(content);
			if(!json.getBoolean("Successful"))
			{
				list = ReadFormCache(context);
				return list;
			}
			JSONArray array = json.getJSONArray("Values");
			for(int i=0;i<array.length();i++)
			{
				JSONObject object = array.getJSONObject(i);
				MessageEntity entity = new MessageEntity();
				if(!object.isNull("ImageURL"))
					entity.ImageURL = object.getString("ImageURL");
				entity.Title = object.getString("Title");
				entity.URL = object.getString("URL");
				if(object.has("Time"))
					entity.Time = object.getString("Time");
				entity.ReadFlag = object.getBoolean("ReadFlag");
				list.add(entity);
			}
			Successful = true;
			if (list.size() > 0)
			{
				Write2Cache(context,array.toString());
			}
		}
		catch (Exception e)
		{
			MobclickAgent.reportError(context, e.getMessage());
			return null;
		}
		return list;
	}
}
